package com.dawn.websocket.client.listener;

import java.net.URI;
import java.net.URISyntaxException;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WSClient extends WebSocketClient {

    static Logger logger = LoggerFactory.getLogger(WSClient.class);

    private String name = null;

    private ClientListener listener = null;

    public WSClient(String url, String name, ClientListener listener) throws URISyntaxException {
        super(new URI(url), new Draft_17());
        this.listener = listener;
        this.name = name;
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        logger.info("{}", "已经与服务器建立连接");
        listener.onOpen(serverHandshake);
        this.send("NAME_" + name);
    }

    @Override
    public void onMessage(String msg) {
        // 接收到服务器反馈的信息,关闭通道
        // logger.info("服务器推送信息，{}", msg);
        if (msg.equals("close")) {
            this.close();
        }
        if (msg.startsWith("succ")) {
            return;
        }
        listener.onMessage(msg);
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        logger.info("连接关闭,{},{},{}", i, s, b);
        listener.onClose(i, s, b);
    }

    @Override
    public void onError(Exception e) {
        logger.error("发生错误，err", e);
        listener.onError(e);
    }

    public static void main(String[] args) {
        String url = "ws://localhost:8002/websocket";

        ClientListener listener = new ClientListenerAdapter() {
            @Override
            public void onMessage(String msg) {
                logger.info("msg:{}", msg);
            }

            @Override
            public void onError(Exception e) {
                logger.error("err", e);
            }
        };

        try {
            WSClient clinet = new WSClient(url, "535", listener);
            boolean res = clinet.connectBlocking();
            if (res) {
                logger.info("{}", "连接成功");
            } else {
                logger.info("{}", "连接失败");
            }
        } catch (URISyntaxException e) {
            logger.error("err", e);
        } catch (InterruptedException e) {
            logger.error("err", e);
        }
    }
}
